package com.example.itcacp.controller;

import com.example.itcacp.dto.response.ApiResponse;
import com.example.itcacp.dto.response.FileNode;
import com.example.itcacp.dto.response.Result;
import com.example.itcacp.entity.*;
import com.example.itcacp.exception.CustomerException;
import com.example.itcacp.repository.mybatis.ProjectMapper;
import com.example.itcacp.service.BrowseHistoryService;
import com.example.itcacp.service.FileService;
import com.example.itcacp.service.ProjectService;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.sql.Timestamp;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/projects")
public class ProjectController {

    @Resource
    private ProjectService projectService;

    @Resource
    private ProjectMapper projectMapper;

    @Resource
    private BrowseHistoryService browseHistoryService;

    /**
     * 创建项目仓库
     */
    @PostMapping("/createProject")
    public Result createProject(@RequestBody Project project) {
        Project project1 = projectMapper.selectProject(project.getUserId(), project.getProjectName());
        if (project1 != null) {
            throw new CustomerException("500", "项目已存在");
        } else {
            try {
                project.setCreatedAt(new Timestamp(System.currentTimeMillis()).toLocalDateTime()); // 设置创建时间
                // 创建仓库
                String gitRepoUrl = projectService.createGitRepo(project.getUserId(), project.getPath());
                project.setPath (gitRepoUrl);  // 设置文件存储路径：绝对路径
                projectService.createProject(project);
                Project newProject = projectMapper.selectProject(project.getUserId(), project.getProjectName());
                return Result.success(newProject);
            } catch (IOException | InterruptedException e) {
                e.printStackTrace();
                return Result.error("创建仓库失败");
            }
        }
    }

    /**
     * 上传文件到仓库
     */
    @PostMapping("/uploadFile/{projectId}")
    public Result uploadFile(@PathVariable Long projectId, @RequestParam("file") MultipartFile file) {
        try {
            projectService.uploadFileToGit(projectId, file);
            return Result.success("文件上传成功");
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
            return Result.error("文件上传失败");
        }
    }

    // 获取所有项目
    @GetMapping("/getAllProjects")
    public Result getAllProjects() {
        List<Project> allProjects = projectService.getAllProjects ();
        return Result.success (allProjects);
    }

    // 获取个人所有项目
    @GetMapping("/selectProjectAllByUserId")
    public Result selectProjectAllByUserId(@RequestParam Long userId) {
        List<Project> projectList = projectService.selectProjectAllByUserId (userId);
        return Result.success (projectList);
    }

    /**
     * 分页查询所有项目
     * */
    @GetMapping("/selectProjectsPage")
    public Result selectProjectsPage (@RequestParam(defaultValue = "1") Integer pageNum,
                                     @RequestParam(defaultValue = "10") Integer pageSize) {
        PageInfo<Project> projectPageInfo = projectService.selectProjectsPage ( pageNum, pageSize );
        return Result.success ( projectPageInfo );
    }

    /**
     * 分页查询个人所有项目
     * */
    @GetMapping("/selectProjectsPageByUser")
    public Result selectProjectsPageByUser (@RequestParam(defaultValue = "1") Integer pageNum,
                                            @RequestParam(defaultValue = "10") Integer pageSize,
                                            @RequestParam Long userId) {
        PageInfo<Project> projectPageInfo = projectService.selectProjectsPageByUser ( pageNum, pageSize, userId );
        return Result.success ( projectPageInfo );
    }

    /**
     * 1. 查询对应类型的所有内容
     * 2. 按照浏览篇内容的浏览记录进行排序,返回前十名
     * 3. 结果返回给前端进行展示，每隔三小时刷新一次
     **/
    @GetMapping("/selectHeat")
    public Result selectHeat () {
        List<Project> allProjects = projectService.getAllProjects ();
        // 按照 views 字段倒序排序，并取前10条
        List<Project> top10List = allProjects.stream()
                .sorted( Comparator.comparingLong((Project p) -> p.getViews() == null ? 0 : p.getViews())
                        .reversed())
                .limit(10)
                .collect( Collectors.toList());
        return Result.success(top10List); // 返回前10条数据
    }

    // 根据ID获取项目
    @GetMapping("/getProjectById/{projectId}")
    public Result getProjectById(@PathVariable Long projectId) {
        Project projectById = projectService.getProjectById ( projectId );
        return Result.success (projectById);
    }

    // 更新项目
    @PutMapping("/updateProject")
    public Result updateProject(@RequestBody Project project) {
        Project project1 = projectService.updateProject ( project );
        return Result.success (project1);
    }

    // 删除项目
    @DeleteMapping("/deleteProject/{projectId}")
    public Result deleteProject(@PathVariable Long projectId) {
        projectService.deleteProject(projectId);
        return Result.success ();
    }



    /**
     * 添加用户感兴趣标签
     * */
    @PostMapping("/addProjectTags")
    public Result addProjectTags(@RequestBody AddRequestBody addRequestBody) {
        Project project = projectMapper.selectProjectById ( addRequestBody.getProject_id () );
        project.setTags ( addRequestBody.tags );
        projectService.updateProject ( project );
        return Result.success ( project );
    }
    // 封装前端请求传递过来的参数数据
    @Data
    static class AddRequestBody {
        private Long project_id;
        private String tags;
    }


    /**
     * 添加历史浏览记录接口
     * */
    @PostMapping("/updateViews")
    public Result updateViews (@RequestBody BrowseHistory browseHistory) {
        browseHistory.setCreated_at ( new Timestamp ( System.currentTimeMillis () ).toLocalDateTime ());
        browseHistoryService.addBrowseHistory ( browseHistory );  //添加点赞记录
        Project projectById = projectService.getProjectById ( browseHistory.getTargetId () );// 查询对应内容
        return Result.success (projectById);  // 返回最新浏览数据
    }





    private final FileService fileService;

    public ProjectController(FileService fileService) {
        this.fileService = fileService;
    }

    @PostMapping("/createFolder")
    public ApiResponse<?> createFolder(@RequestBody CreateFolderRequest request) {
        // 拿到项目id，查询该用户下的对应仓库，进行添加文件夹
        return fileService.createFolder(request.projectId, request.getFolderName());
    }

    @GetMapping("/getFileTree/{projectId}")
    public ApiResponse<FileNode> getFileTree(@PathVariable Long projectId) throws IOException {
        return fileService.getFileTree(projectId);
    }

    // 请求内部类
    private static class CreateFolderRequest {
        private Long projectId;
        private String folderName;

        public Long getProjectId() {
            return projectId;
        }

        public void setProjectId(Long projectId) {
            this.projectId = projectId;
        }

        public String getFolderName() {
            return folderName;
        }

        public void setFolderName(String folderName) {
            this.folderName = folderName;
        }
    }

}